import React, { useEffect, useState } from 'react';
import { getLoadMapList, getTenantID, getSelectDataMapList, splitFileUrl, downloadTemplate, getFileNameNotType, getUserDepID, removeDateHmsStr } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import { Form, Select, Tooltip, TreeSelect, message, Button } from 'antd';
import TransferView from '../mview/TransferView';
import { UploadFormCommon } from '@/components/UploadForm';
import MyIcon from '@/components/MyIcon';
import { getFlowOrgTreeByOrgIDService } from '@/services/BaseLayout';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const ThemeContext = React.createContext({});

const getUpdateConfig = ({
  pageType,
  record,
  detailInfo,
  contractForm,
  changeGetUser,
  getUserLoading,
  getUserList,
  getSelectUserInfo,
  openMaterialModalStatus,
  openReadAssetModalFun,
}) => {
  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();
  // 内部还是跨部门
  const [isIntoDep, setIsIntoDep] = useState<boolean>(true);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
  ]);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {}, []);

  /** 切换表单 */
  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    const userDepID = getUserDepID(); // 当前登陆人部门id
    let departIdTemp: any = '';
    let departIdTempNow: any = '';
    // 如果是新增 使用登陆人的部门
    if (pageType === 'add') {
      departIdTemp = userDepID;
      departIdTempNow = userDepID;
      changeGetUser(userDepID);
      // 回填表单
      contractForm?.setFieldsValue({
        ...record,
        createTime: moment(record),
        allotType: 1,
        originalDepartmentID: departIdTemp, // 原部门
        // newDepartmentID: undefined, // 现部门
        // newerID: undefined,//使用人
        // createTime: moment(record?.createTime),
      });
    } else {
      departIdTemp = record.originalDepartmentID;
      departIdTempNow = record.newDepartmentID;
      setIsIntoDep(record.allotType == 1);
      changeGetUser(record.newDepartmentID);
      getSelectUserInfo(record, {
        userCompanyID: record.newCompanyID || '',
        userPositionID: record.newPositionID || '',
      }); // 提交使用数据
      // 回填表单
      contractForm?.setFieldsValue({
        ...detailInfo,
        createTime: moment(detailInfo),
      });
    }
  }, [pageType, detailInfo]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: contractForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 0,
          },
          {
            field: `allotType`,
            label: `交接类型`,
            component: 'Render',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 2,
            render: (text) => {
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'allotType'}
                  defalultKeys={Number(text)}
                  radioDisabled={disabled}
                  onChange={(value) => {
                    if (value == 1) {
                      const userDepID = getUserDepID(); // 当前登陆人部门id
                      contractForm?.setFieldsValue({
                        originalDepartmentID: userDepID, // 原部门
                        newDepartmentID: userDepID, // 现部门
                      });
                      changeGetUser(userDepID);
                      setIsIntoDep(true);
                    } else {
                      const userDepID = getUserDepID(); // 当前登陆人部门id
                      contractForm?.setFieldsValue({
                        originalDepartmentID: userDepID, // 原部门
                        newDepartmentID: undefined, // 现部门
                      });
                      changeGetUser('');
                      setIsIntoDep(false);
                    }
                  }}
                  radioList={[
                    {
                      value: 1,
                      name: '在用资产交接(部门内)',
                    },
                    {
                      value: 2,
                      name: '在用资产调剂(跨部门)',
                    },
                    {
                      value: 3,
                      name: '闲置资产调剂(跨部门)',
                    },
                  ]}
                />
              );
            },
          },
          {
            field: 'originalDepartmentID',
            label: `移交使用部门`,
            required: !disabled,
            component: 'TreeSelect',
            disabled: disabled,
            placeholder: '请选择',
            messageTrue: '请选择移交使用部门',
            ishidden: isIntoDep,
            loading: getFlowOrgTreeLoading,
            treeData: handleNotPostion(getFlowOrgList),
            showArrow: pageType == 'detail' ? false : true,
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            } as any,
            showSearch: true,
            treeNodeFilterProp: 'text',
            allowClear: true,
          },
          {
            field: `newDepartmentID`,
            label: `接收使用部门`,
            disabled: disabled,
            component: 'TreeSelect',
            required: !disabled,
            ishidden: isIntoDep,
            messageTrue: '请选择接收使用部门',
            loading: getFlowOrgTreeLoading,
            placeholder: '请选择',
            treeData: handleNotPostion(getFlowOrgList),
            showArrow: pageType == 'detail' ? false : true,
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            } as any,
            showSearch: true,
            treeNodeFilterProp: 'text',
            allowClear: true,
            onChange: (value: string | number) => {
              changeGetUser(value);
            },
          },
          {
            field: `newerID`,
            label: `接收使用人`,
            disabled: disabled,
            component: 'Render',
            required: !disabled,
            contentAfter: <a onClick={() => openReadAssetModalFun(methods?.getFieldValue('newerID'))}>名下资产</a>,
            colSpan: 2,
            messageTrue: '请选择接收使用人',
            render: (text) => {
              if (pageType === 'detail') {
                return <span>{record.newerName || '--'}</span>;
              } else {
                return (
                  <Select
                    placeholder="请选择"
                    defaultValue={text}
                    loading={getUserLoading}
                    options={getUserList}
                    disabled={disabled}
                    fieldNames={{
                      label: 'realName',
                      value: 'id',
                    }}
                    onChange={(value: number | string, option: any) => {
                      getSelectUserInfo(value, option);
                    }}
                  />
                );
              }
            },
          },
          {
            field: `applyInfo`,
            label: `申请理由`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: !disabled,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            placeholder: '请上传',
            colSpan: 2,
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={contractForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        // console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: (
          <TransferView pageType={pageType} openMaterialModalStatus={openMaterialModalStatus} mapLoading={mapLoading} loadMapInfo={loadMapInfo} />
        ),
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig, ThemeContext };

// {
//   field: 'originalDepartmentID',
//   label: `移交使用部门`,
//   required: !disabled,
//   component: 'Render',
//   disabled: disabled,
//   // placeholder: '请选择',
//   messageTrue: '请选择移交使用部门',
//   ishidden: isIntoDep,
//   render: (text) => {
//     return (
//       <TreeSelect
//         id={"originalDepartmentID" + new Date()?.getTime()}
//         loading={getFlowOrgTreeLoading}
//         placeholder="请选择"
//         treeData={handleNotPostion(getFlowOrgList)}
//         disabled={pageType == 'detail' ? true : false}
//         showArrow={pageType == 'detail' ? false : true}
//         fieldNames={{
//           label: 'title',
//           value: 'id',
//           children: 'children',
//         }}
//         showSearch={true}
//         treeNodeFilterProp={'text'}
//         allowClear={true}
//       />
//     );
//   },
// },
// {
//   field: `newDepartmentID`,
//   label: `接收使用部门`,
//   // placeholder: '请选择',
//   disabled: disabled,
//   component: 'Render',
//   required: !disabled,
//   ishidden: isIntoDep,
//   messageTrue: '请选择接收使用部门',
//   render: (text) => {
//     return (
//       <TreeSelect
//         id={"newDepartmentID" + new Date()?.getTime()}
//         loading={getFlowOrgTreeLoading}
//         placeholder="请选择"
//         treeData={handleNotPostion(getFlowOrgList)}
//         disabled={pageType == 'detail' ? true : false}
//         showArrow={pageType == 'detail' ? false : true}
//         fieldNames={{
//           label: 'title',
//           value: 'id',
//           children: 'children',
//         }}
//         showSearch={true}
//         treeNodeFilterProp={'text'}
//         allowClear={true}
//         onChange={(value: string | number) => {
//           changeGetUser(value);
//         }}
//       />
//     );
//   },
// },
// {
//   field: `newerID`,
//   label: `接收使用人`,
//   disabled: disabled,
//   component: 'Render',
//   required: !disabled,
//   contentAfter: <a onClick={() => openReadAssetModalFun(methods?.getFieldValue('newerID'))}>名下资产</a>,
//   colSpan: 2,
//   // placeholder: '请选择',
//   messageTrue: '请选择接收使用人',
//   render: (text) => {
//     if (pageType === 'detail') {
//       return <span>{record.newerName || '--'}</span>;
//     } else {
//       return (
//         <Select
//           // placeholder="请选择"
//           defaultValue={text}
//           loading={getUserLoading}
//           options={getUserList}
//           disabled={disabled}
//           fieldNames={{
//             label: 'realName',
//             value: 'id',
//           }}
//           onChange={(value: number | string, option: any) => {
//             getSelectUserInfo(value, option);
//           }}
//         />
//       );
//     }
//   },
// },
